﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using Dln.Common.WxPayAPI;
using Dln.Common;
using Dln.Business;
using Dln.Common.Helper;
using Dln.Handler;
using System.Text;
using Dln.Model;

public partial class Page_OrderPay_Jspay : System.Web.UI.Page
{
    //protected static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    protected string MainUrl = CommonHelper.GetAppSettings("mainurl");
    public static string APPID = CommonHelper.GetAppSettings("AppID");
    public static string time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
    public static string noncestr = string.Empty, resp = string.Empty;
    public static string wxJsApiParam { get; set; } //H5调起JS API参数
    public object ticket = null;
    public string backUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        var orderno = DNTRequest.GetString("orderno");
        var openid = DNTRequest.GetString("openid");

        backUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port + Request.RawUrl;
        noncestr = RandString();
        time = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

        ticket = HttpContext.Current.Session["getticket"];
        if (ticket == null || ticket == "")
        {
            string newjson = RequestHelper.SendGet(String.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", WeiXinConfig.AccessToken));
            WinXinShareBusiness.GetTicket getticket = null;
            if (!String.IsNullOrEmpty(newjson))
            {
                try
                {
                    getticket = JSONHelper.FromJson<WinXinShareBusiness.GetTicket>(newjson);
                }
                catch (Exception ex)
                {

                }
            }
            ticket = getticket.ticket;
            HttpContext.Current.Session["getticket"] = ticket;
            HttpContext.Current.Session.Timeout = 20;
        }
        string string1 = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, noncestr, time, backUrl);
        resp = SHA1(string1);

        Log.Debug(this.GetType().ToString(), "Line28,code=" + "支付开始"+ backUrl);

        //若传递了相关参数，则调统一下单接口，获得后续相关接口的入口参数
        JsApiPay jsApiPay = new JsApiPay(this) { openid = openid, total_fee = 200 };
        //JSAPI支付预处理
        try
        {
            WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(orderno);
            wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数             

            Log.Debug(this.GetType().ToString(), "wxJsApiParam:" + wxJsApiParam.ToString());

            //Response.Write("<span style='color:#00CD00;font-size:20px'>" + unifiedOrderResult.ToPrintStr() + "</span>");
        }
        catch (Exception ex)
        {
            Log.Debug(this.GetType().ToString(), "微信支付失败:" + ex.ToString());

            //Response.Redirect(string.Format("JsApiPayPage.aspx?orderno={0}&openid={1}", orderno, openid), true);
        }
    }

    protected static string RandString()
    {
        string str = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//62个字符
        Random r = new Random();
        string result = string.Empty;

        //生成一个8位长的随机字符，具体长度可以自己更改
        for (int i = 0; i < 16; i++)
        {
            int m = r.Next(0, 62);//这里下界是0，随机数可以取到，上界应该是75，因为随机数取不到上界，也就是最大61，符合我们的题意
            string s = str.Substring(m, 1);
            result += s;
        }

        return result;
    }

    private static string SHA1(string text)
    {
        byte[] cleanBytes = Encoding.Default.GetBytes(text);
        byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
        return BitConverter.ToString(hashedBytes).Replace("-", "");
    }
}